<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\ScienceModel;
use app\common\model\ScienceCategoryModel;
use app\common\model\ScienceLikeModel;
use app\common\model\ScienceReportModel;
use app\common\model\user\UserModel;
use app\common\model\NoticeModel;
use app\api\service\ScienceService;
use think\Request;
use think\response\Json;

class Science extends Controller
{
    /**
     * 获取科普文章列表
     * @param Request $request
     * @return Json
     */
    public function lists(Request $request): Json
    {
        $categoryId = (int) $request->get('category_id', 0);
        $page = (int) $request->get('page', 1);
        $size = (int) $request->get('size', 10);
        $keyword = (string) $request->get('keyword', '');    
        $query = ScienceModel::where('status', 1)
            ->with(['category' => function($query) {
                $query->field('id, name');
            },'user' => function($query) {
                $query->field('id, name, avatar');
            }]);

         if($keyword){
            $query->where('title', 'like', '%' . $keyword . '%');
         }

        if ($categoryId > 0) {
            $query->where('category_id', $categoryId);
        }
        
        $count = $query->count();
        $list = $query->order('publish_time', 'desc')
            ->page($page, $size)
            ->field('id, title, source, views, likes, publish_time, cover_image, category_id, user_id, disclaimer')
            ->select();
        // 使用服务层格式化数据
        $formattedList = [];
        foreach ($list as $article) {
            $formattedList[] = ScienceService::formatArticle($article->toArray(), $request->uid);
        }
        
        return success('success', [
            'list' => $formattedList,
            'total' => $count,
            'page' => $page,
            'size' => $size
        ]);
    }
    
    /**
     * 获取文章详情
     * @param Request $request
     * @return Json
     */
    public function detail(Request $request): Json
    {
        $id = (int) $request->get('id', 0);
        
        if ($id <= 0) {
            return error('参数错误');
        }
        
        $article = ScienceModel::where('id', $id)
            ->where('status', 1)
            ->with(['category' => function($query) {
                $query->field('id, name');
            },'user' => function($query) {
                $query->field('id, name, avatar');
            }])
            ->find();
        
        if (!$article) {
            return error('文章不存在');
        }
        
        // 增加浏览量
        $article->views += 1;
        $article->save();
        $uid  = $article['user_id'];
       
    
        
        // 使用服务层格式化数据，传入用户ID以支持关注状态
        $formattedArticle = ScienceService::formatArticle($article->toArray(), $uid);
        $formattedArticle['contentCount'] = ScienceModel::where('user_id',$uid)->count();
        return success('success', $formattedArticle);
    }
    
    /**
     * 获取文章分类列表
     * @return Json
     */
    public function categories(): Json
    {
        $categories = ScienceCategoryModel::field('id, name')
            ->order('id', 'asc')
            ->select();
        
        return success('success', $categories);
    }
    
    /**
     * 点赞文章（支持取消点赞）
     * @param Request $request
     * @return Json
     */
    public function like(Request $request): Json
    {
        $id = (int) $request->post('id', 0);
        $uid = $request->uid; // 获取用户ID
        
        if ($id <= 0 || $uid <= 0) {
            return error('参数错误');
        }
        
        $article = ScienceModel::where('id', $id)
            ->where('status', 1)
            ->find();
        
        if (!$article) {
            return error('文章不存在');
        }
        
        // 检查用户是否已点赞
        $likeModel = new ScienceLikeModel();
        $liked = $likeModel::where('user_id', $uid)
            ->where('article_id', $id)
            ->find(); 
        if ($liked) {
            // 已点赞，取消点赞
            $liked->delete();
            $article->likes -= 1;
            $message = '取消点赞成功';
        } else {
            // 未点赞，进行点赞
            $likeData = [
                'user_id' => $uid,
                'article_id' => $id,
                'create_time' => time()
            ];
            $likeModel->save($likeData);
            $article->likes += 1;
            $message = '点赞成功';
        }
        
        $article->save();
        
        return success($message, ['likes' => $article->likes, 'is_liked' => $liked ? 0 : 1]);
    }
    
    /**
     * 搜索文章
     * @param Request $request
     * @return Json
     */
    public function search(Request $request): Json
    {
        $keyword = trim((string) $request->get('keyword', ''));
        $page = (int) $request->get('page', 1);
        $size = (int) $request->get('size', 10);
        
        // 使用服务层搜索文章
        $result = ScienceService::searchArticles($keyword, $page, $size);
        
        return success('success', $result);
    }
    
    /**
     * 获取热门文章
     * @param Request $request
     * @return Json
     */
    public function hot(Request $request): Json
    {

        $page = (int) $request->get('page', 1);
        $size = (int) $request->get('size', 10);
        $uid = $request->uid; // 获取用户ID
        // 使用服务层获取热门文章
        $hotArticles = ScienceService::getHotArticles($uid, $page, $size);
        
        return success('success', $hotArticles);
    }

    /**
     * 获取精选科普文章
     * @param Request $request
     * @return Json
     */
    public function featured(Request $request): Json
    {
        $page = (int) $request->get('page', 1);
        $size = (int) $request->get('size', 10);
        
        $articles = ScienceModel::where('status', 1)
            ->where('featured', 1) // 假设featured字段表示是否精选
            ->with(['category' => function($query) {
                $query->field('id, name');
            },'user' => function($query) {
                $query->field('id, name, avatar');
            }])
            ->order('publish_time', 'desc')
            ->page($page, $size)
            ->field('id, title, source, views, likes, publish_time, cover_image, category_id, user_id')
            ->select();
        
        $count = ScienceModel::where('status', 1)
            ->where('featured', 1)
            ->count();
        
        $formattedList = [];
        foreach ($articles as $article) {
            $formattedList[] = ScienceService::formatArticle($article->toArray(), $request->uid);
        }
        
        return success('success', [
            'list' => $formattedList,
            'total' => $count,
            'page' => $page,
            'size' => $size
        ]);
    }

    /**
     * 举报科普文章
     * @param Request $request
     * @return Json
     */
    public function report(Request $request): Json
    {
        $uid = $request->uid;
        $reason = $request->post('reason', '');
        $id = $request->post('id', 0);
        
        if ($id <= 0 || empty($reason)) {
            return error('参数错误');
        }
        
        $article = ScienceModel::where('id', $id)
            ->where('status', 1)
            ->find();
        
        if (!$article) {
            return error('文章不存在');
        }
        
        // 不能举报自己的文章
        if ($article['user_id'] == $uid) {
            return error('您不能举报您自己的文章！');
        }
        
        // 标记文章状态为待审核
//        $article->status = 3;
//        $article->save();
        
        // 发送通知给文章作者
        $contentUrl = '/pages/science/detail?id=' . $id;
        $content = '您的科普文章《' . $article['title'] . '》因"' . $reason . '"被举报，请修改后重新发布，否则无法获得更多曝光。';
        (new NoticeModel())->send($article['user_id'], '文章违规', $content, 0, '', $contentUrl, 1);
        
        // 触发举报事件（可用于后续处理）
        event('ReportScience', ['id' => $id, 'reason' => $reason, 'user_id' => $uid]);
        
        return success('提交成功，感谢您的举报！');
    }
}